package tool;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServlet;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import exception.Exceptions;

@SuppressWarnings("serial")
public class WordDownload extends HttpServlet{
	private Map<String, String> map=new HashMap<String, String>();
	private String wordmodel;
	
	public  void setWord(Map<String, String> map,String wordmodel){
		this.wordmodel=wordmodel+".doc";
		this.map=map;
	}

	public InputStream run() throws Exceptions{
		try {
			String fileDir = new File(this.getClass().getResource("").getFile(),"../../../data/word/").getCanonicalPath();
			fileDir=fileDir.replaceAll("%20"," ");
			FileInputStream in = new FileInputStream(new File(fileDir+"/"+wordmodel));
			HWPFDocument hdt =  new HWPFDocument(in);

			//下面不知做什么用，先注释
			/*			 
			import org.apache.poi.hwpf.model.FieldsDocumentPart;
			import org.apache.poi.hwpf.usermodel.Field;
			import org.apache.poi.hwpf.usermodel.Fields;
			import java.util.Iterator;
			import java.io.FileNotFoundException;
			Fields fields = hdt.getFields();
			Iterator<Field> it = fields.getFields(FieldsDocumentPart.MAIN).iterator();
			while(it.hasNext()){
				System.out.println("~~~~~~~~~~~~~~~"+it.next().getType());
			}*/
			
			//替换读取到的word模板内容的指定字段
			Range range = hdt.getRange();
			for (Map.Entry<String,String> entry:map.entrySet()) {
				range.replaceText("${"+entry.getKey().trim()+"}",entry.getValue());
			}
			
			//输出word内容文件流，提供下载
			ByteArrayOutputStream baos = new ByteArrayOutputStream();  

        	hdt.write(baos);
            byte[] ba = baos.toByteArray();  
            ByteArrayInputStream bais = new ByteArrayInputStream(ba);
            return bais;
        } catch (IOException e) {  
            //e.printStackTrace();
        	throw new Exceptions("");
        }  
	}

}
